<script setup lang="ts">
import * as echarts from 'echarts'
import { onMounted, watch, nextTick, onBeforeUnmount } from 'vue'
import { useDialogStore } from '@/stores/dialog'
import {
  DEFAULT_ECHARTS_FONTSIZE,
  DIALOG_ECHARTS_FONTSIZE,
} from '@/Utils/setting'
const dialogStore = useDialogStore()
const { dialogInfo } = dialogStore

const fontSize = dialogInfo.visible
  ? DIALOG_ECHARTS_FONTSIZE
  : DEFAULT_ECHARTS_FONTSIZE
const dialogInfoVisible = dialogInfo.visible
// 调整px到合适的大小
const changePixelSize = (px: number) => {
  // 获取当前屏幕宽度
  const width = document.body.clientWidth
  let res = (px / 1920) * width
  // 保留整数
  return parseInt(res.toFixed(0))
}

// 接收父组件的数据
const props = defineProps<{
  chartData: any
}>()
props.chartData.name = props.chartData.name + Math.random()
var myChart

// 绘制图表
const drawChart = () => {
  if (myChart != null && myChart != '' && myChart != undefined) {
    myChart.dispose() //解决echarts dom已经加载的报错
  }

  // 绘制新图表
  myChart = echarts.init(document.getElementById(props.chartData.name))
  let option = {
    tooltip: {
      confine: true, // true后,弹出的提示不超出图表
      trigger: props.chartData?.tooltip?.trigger || 'axis',
      backgroundColor: 'rgba(0,0,0,0.7)', //默认值，提示背景颜色，默认为透明度为0.7的黑色
      padding: [
        changePixelSize(10), // 上
        changePixelSize(20), // 右
        changePixelSize(10), // 下
        changePixelSize(20), // 左
      ],

      textStyle: {
        fontSize: changePixelSize(fontSize),
        color: '#fff', //设置文字颜色
      },
      axisPointer: {
        type: 'none',
      },
    },
    dataZoom: props.chartData.dataZoom,
    legend: props.chartData.legend,
    grid: props.chartData.grid,
    xAxis: props.chartData.xAxis,
    yAxis: props.chartData.yAxis,
    series: props.chartData.series,
  }
  myChart.setOption(option)
}
const destroyChart = () => {
  // 销毁图表实例
  if (myChart) {
    myChart.dispose()
    myChart = null
  }
}
onBeforeUnmount(() => {
  // 销毁图表实例
  destroyChart()
})
// 组件挂载后绘制图表
onMounted(() => {
  nextTick(() => {
    drawChart()
  })
})
</script>

<template>
  <div
    :class="{
      'echart-box': true,
      'bottom-box': chartData.position == 'bottom',
      'dialog-box': dialogInfoVisible == true,
    }"
  >
    <div class="chart" :id="chartData.name"></div>
  </div>
</template>

<style lang="scss" scoped>
.echart-box {
  position: relative;
  width: 100%;
  height: calc(
    260px - 45px
  ); // 45px 是标题 35 高度+10px 轮播图指示器预留空间高度
  .chart {
    width: 100%;
    height: 100%;
  }
}
.bottom-box {
  height: calc(
    210px - 45px
  ); // 45px 是标题 35 高度+10px 轮播图指示器预留空间高度
}
.dialog-box {
  height: calc(
    500px - 45px
  ); // 45px 是标题 35 高度+10px 轮播图指示器预留空间高度
}
</style>
